#ifndef __MY_DATA__
#define __MY_DATA__
#include"util.hpp"
#include<string>
#include<sstream>
#include<unordered_map>
namespace cloud
{
	class DataManager
	{
	public:
		DataManager(const std::string& backup_file)
			:_backup_file(backup_file)
		{
			InitLoad();
		}

		bool Storage()
		{
			
			std::stringstream ss;
			for (auto e : _table)
			{
				ss << e.first << " " << e.second << "\n";
			
			}

			FileUtil fu(_backup_file);
			fu.SetContent(ss.str());

			return true;
		}

		bool InitLoad()
		{
			FileUtil fu(_backup_file);
			if (fu.Exists() == false)
			{
				return true;
			}
			std::string body;
			fu.GetContent(&body);

			size_t pos=body.find("\n");
			size_t begin = 0;
			size_t len = pos-begin;
			while (pos != body.npos)
			{
				std::string str = body.substr(begin, len);
				begin = pos + 1;
				pos=body.find("\n",begin);
				len = pos - begin;

				Insert(str.substr(0, str.find(" ")), str.substr(str.find(" ") + 1));
			}

			return true;
			/*FileUtil file(_backup_file);
			if (file.Exists() == false)
			{
				return true;
			}
			std::ifstream ifs(_backup_file);
			std::string key, value;
			while (ifs >> key >> value)
			{
				Insert(key, value);
			}

			ifs.close();

			return true;*/
		}

		bool Insert(const std::string& key, const std::string& value)
		{
			_table[key] = value;
			Storage();
			return true;
		}


		bool Update(const std::string& key, const std::string& value)
		{
			_table[key] = value;
			Storage();
			return true;
		}


		bool GetOneByKey(const std::string& key, std::string* value)
		{
			auto it=_table.find(key);
			if (it == _table.end())
			{
				return false;
			}
			*value = it->second;
			return true;
		}


	private:
		std::string _backup_file;
		std::unordered_map<std::string, std::string> _table;
	};
}

#endif
